package com.xfgg.hot.dlc.aop;

import com.github.benmanes.caffeine.cache.Cache;
import com.xfgg.hot.dlc.cache.LocalCache;
import com.xfgg.hot.dlc.cache.OhcCache;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.caffinitas.ohc.OHCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xfgg
 */
@Aspect
@Component
public class RedisAspect extends LocalCache {
    @Autowired
    private OhcCache ohcCache;

    private static final ConcurrentHashMap<String, Integer> COUNT_MAP = new ConcurrentHashMap<>();
    private static final int DEFAULT_SIZE = 10;

    @Pointcut("@annotation(redisHot)")
    public void callAt(RedisHot redisHot) {

    }

    @After(value = "callAt(redisHot)", argNames = "redisHot")
    public void beforeCallAt(RedisHot redisHot) {
        String key = redisHot.key();
        String result = redisHot.result();
        Integer count = incrementAndGet(key);
        Cache<String, Object> stringObjectCache = super.buildRedisCache(COUNT_MAP);
        OHCache<String, Object> basicStoreInfoCache = ohcCache.getBasicStoreInfoCache();
        basicStoreInfoCache.put(key, result);
        if (count > DEFAULT_SIZE) {
            stringObjectCache.put(key, result);
        }
    }

    public Integer incrementAndGet(String key) {
        return COUNT_MAP.compute(key, (k, v) -> v == null ? 1 : v + 1);
    }
}
